<!--
图像截取 https://github.com/xyxiao001/vue-cropper
-->
<template>
<div>
    <Upload :action="action" :before-upload="onBeforeUpload" :accept="config.accept" :max-size="config.maxSize" :format="config.format" :with-credentials="false" :multiple="multiple" type="select">
        <slot></slot>
    </Upload>
    <Modal :mask-closable="false" v-model="isShowCropperModal" title="图像裁剪" @on-ok="doCropper" @on-cancel="cancelCropper">
        <VueCropper :style="{'height':cropper.vueCropperHeight + 'px'}" ref="cropper" :img="cropper.imgBase64Data" :outputSize="cropper.outputSize" :outputType="cropper.outputType" :fixed="cropper.fixed" :fixedBox="cropper.fixedBox" :autoCrop="cropper.autoCrop"
            :autoCropWidth="cropper.autoCropWidth" :autoCropHeight="cropper.autoCropHeight" :original="cropper.original"></VueCropper>
    </Modal>
</div>
</template>

<script>
import AppFrame from '../libs/app-frame';
import VueCropper from 'vue-cropper';
export default {
    name: 'm-upload',
    components: {
        VueCropper
    },
    props: {
        action: { //上传的地址，必填
            required: true,
            type: String,
            default: '/base/upload/file'
        },
        multiple: {
            type: Boolean,
            default: false
        },
        accept: {
            type: String,
            default: ''
        },
        fileType: { //上传类型
            type: String,
            default: 'file'
        },
        cropperSize: {
            type: Array,
            default: null
        },
        dir:{default:''},//指定存储目录
        value: '',
    },
    model: {
        prop: 'value',
        event: 'updateVal'
    },

    data: function() {
        return {

            isShowCropperModal: false,
            uploadConfig: {},
            config: {
                maxSize: 0,
                format: [],
                accept: ''
            },
            cropper: {
                outputSize: 1,
                imgBase64Data: '',
                outputType: 'png',
                autoCrop: true,
                autoCropWidth: 0,
                autoCropHeight: 0,
                fixed: false, //固定截图款宽高比例
                fixedBox: true, //固定截图框大小
                canMoveBox: true,
                original: false,
                vueCropperHeight: 0 //控件高度
            }


        }
    },
    created() {
        this.init();

    },
    methods: {
        init() {
            this.getConfig();
            if (this.cropperSize && this.cropperSize.length > 0) {
                this.cropper.autoCropWidth = this.cropperSize[0];
                this.cropper.autoCropHeight = this.cropperSize[1];
                this.cropper.vueCropperHeight = this.cropper.autoCropHeight + 20;

            }
        },

        getConfig: async function() {
            let self = this;
            try {
                let ret = await AppFrame.Http.Post("/base/upload/config", {});
                this.uploadConfig = ret;

                if (ret) {
                    switch (self.fileType) {
                        case 'img':
                            self.config.maxSize = ret.imageMaxSize;
                            self.config.format = ret.imageAllowFiles;
                            self.config.accept = "image/*";
                            break;
                        case 'video':
                            self.config.maxSize = ret.videoMaxSize;
                            self.config.format = ret.videoAllowFiles;
                            self.config.accept = "video/*";
                            break;
                        default:
                            self.config.maxSize = ret.fileMaxSize;
                            self.config.format = ret.fileAllowFiles;
                            self.config.accept = "";
                            break;
                    }
                } else {
                    this.$Message.error('上传配置获取失败');
                }
            } catch (err) {
                console.log(err);
                this.$Message.error(JSON.stringify(err));
            }

        },

        onBeforeUpload: function(file) {
            //console.log(file);
            let self = this;
            if (file.size > this.config.maxSize) {
                this.$Message.error("图片超出大小限制 " + this.config.maxSize / 1000 + "KB");
                return false;
            };

            let ext = "." + file.name.split('.')[1];
            if (!this.checkAllowFiles(ext)) {
                this.$Message.error("选择了不允许的文件格式");
                return false;
            };

            let reader = new FileReader(); //声明一个FileReader实例 
            reader.readAsDataURL(file); //调用readAsDataURL方法来读取选中的图像文件 
            reader.onload = function(e) {
                if (window.FileReader && self.fileType == "img" && self.cropper.autoCropWidth > 0) {
                    self.cropper.imgBase64Data = e.target.result;
                    self.isShowCropperModal = true;
                } else {
                    self.doUpload(e.target.result);
                }
            }
        },

        doUpload: async function(data, cb) {
            try {
                let self=this;
                let postData = {};
                postData[this.uploadConfig.scrawlFieldName] = data;
                this.$Message.loading({
                    content: '请稍等',
                    duration: 0
                });
                 AppFrame.Http.Post("/base/upload/image?contentType=base64", postData,function(err,ret){
                   self.$Message.destroy()
                   if(ret && ret.state=='SUCCESS'){
                         self.setValue(ret.url);
                     }
                 });
            } catch (err) {
                console.log(err);
                 this.$Message.error('删除失败，请重试');
            }

        },

        doCropper: async function() {
            let self = this;
            this.$refs.cropper.startCrop();
            this.$refs.cropper.getCropData(async function(data) {
                self.doUpload(data);
            })
        },

        cancelCropper: function() {},

        setValue: function(val) {
            this.$emit("updateVal", val);
        },

        checkAllowFiles: function(ext) {
            var index = this.config.format.findIndex((item) => {
                return item == ext
            });
            if (index == -1) {
                return false;
            }
            return true;
        }
    }
}
</script>

<style scoped>

</style>